package com.example.service.impl;

import com.example.pojo.ResultBean;
import com.example.pojo.SysUserRole;
import com.example.mapper.SysUserRoleMapper;
import com.example.service.ISysUserRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lyj
 * @since 2023-02-16
 */
@Service
public class SysUserRoleServiceImpl extends ServiceImpl<SysUserRoleMapper, SysUserRole> implements ISysUserRoleService {

    /**
     * 分配角色
     * @param userId
     * @param roleIds
     * @return
     */
    @Override
    @Transactional
    public boolean assignRoles(Serializable userId, List<Serializable> roleIds) {
        //根据userId删除用户角色表的相关数据
        boolean remove = this.lambdaUpdate().eq(SysUserRole::getUserId, userId).remove();
        //构造用户角色对象集合
        List<SysUserRole> sysUserRoles = new ArrayList<>();
        for (Serializable roleId : roleIds) {
            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setUserId((Long.parseLong(userId.toString())));
            sysUserRole.setRoleId(Long.parseLong(roleId.toString()));
            sysUserRoles.add(sysUserRole);
        }
        //重新批量插入
        boolean saveBatch = this.saveBatch(sysUserRoles);
        return saveBatch;
    }
}
